package cn.yogehaoren.demo.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author WangNing
 * @since 1.0
 */
@Component
public class RabbitMQReceiver {


    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "queue-1", durable = "true", exclusive = "false", autoDelete = "false"),
            exchange = @Exchange(value = "exchange-1", durable = "true", type = "topic", autoDelete = "false"),
            key = "springboot.#"
    )})
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception{
        System.out.println("------------------ Consumer(rawMessage) -----------------");
        System.out.println("消费端：" + new String(message.getBody()));
        long tag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(tag, true);
    }


    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "${consumer.queue}", durable = "true", exclusive = "false", autoDelete = "false", ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(value = "${consumer.exchange}", durable = "true", type = "topic", autoDelete = "false", ignoreDeclarationExceptions = "true"),
            key = "${consumer.routingKey}"
    )})
    @RabbitHandler
    public void onMessage(@Payload String order, Channel channel, @Headers Map<String , Object> headers) throws Exception{
        System.out.println("------------------ Consumer(Order) -----------------");
        System.out.println("消费端：" +order);
        long tag = (long)headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(tag, true);

    }

}
